package com.whynot.frame.basic.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.StandardServletEnvironment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class YmlUtil {

    private static final String SPLIT_STR = ".";

    private static Map<String,String> ymlMap = new HashMap<>();

    @Autowired
    SpringUtil springUtil;

    @Autowired
    Environment environment;

    public List<Object> getListByKey(String key){
        Map<String, Object> map = new HashMap<>();
        map.putAll(getList());
        List<Object> list = new ArrayList<>();
        map.forEach((k,v)->{
                if(k.toString().startsWith(key)){
                    list.add(v);
                }
            }
        );
        return list;
    }

    public Map<String,String> getMapByKey(String key){
        Map<String, Object> map = new HashMap<>();
        map.putAll(getList());
        Map<String,String> ret = new HashMap<>();
        map.forEach((k,v)->{
                    if(k.toString().startsWith(key)){
                        ret.put(k.split(key+SPLIT_STR)[0],v.toString());
                    }
                }
        );
        return ret;
    }

    private Map<String, String> getList(){
        PropertySource source = ((StandardServletEnvironment) environment).getPropertySources()
                .get("applicationConfig: [classpath:/application.yml]");
        Map<String, String> appMap = (Map<String, String>) source.getSource();

        if (environment.getActiveProfiles().length > 0) {
            PropertySource activeSource = ((StandardServletEnvironment) environment).getPropertySources()
                    .get("applicationConfig: [classpath:/application-" + environment.getActiveProfiles()[0] +
                            ".yml]");
            Map<String, String> activeAppMap = (Map<String, String>) activeSource.getSource();
            appMap.putAll(activeAppMap);
        }
        return appMap;
    }
}
